package com.feri.ssm.service.impl;
import com.feri.ssm.dao.PetDao;
import com.feri.ssm.dto.PetMsgDto;
import com.feri.ssm.entity.Pet;
import com.feri.ssm.service.intf.PetService;
import com.feri.ssm.vo.PageVo;
import com.feri.ssm.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Service
public class PetServiceImpl implements PetService {
    @Resource
    private PetDao dao;

    //新增
    @Override
    public R save(Pet pet) {
        if(dao.add(pet) > 0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    //删除
    @Override
    public R del(int id) {
        if(dao.del(id) > 0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    //修改
    @Override
    public R update(Pet pet) {
        if(dao.update(pet) > 0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    //查询
    @Override
    public PageVo selectAll(int page, int limit) {
        //
        PageHelper.startPage(page, limit);
        PageInfo<Pet> pageInfo =new PageInfo<>(dao.selectAll());
        //3.返回
        return PageVo.ok(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public PageVo selectAll2(String name, String msgName, Integer page, Integer limit) {
        //
        PageHelper.startPage(page,limit);
        PageInfo<PetMsgDto> pageInfo =new PageInfo<>(dao.selectById2(name, msgName));
        //3.返回
        return PageVo.ok(pageInfo.getTotal(),pageInfo.getList());
    }

    //导出数据
    @Override
    public void exportData(HttpServletResponse response) throws IOException {
        //1.设置下载的文件名
        String s1 = "宠物信息-"+System.currentTimeMillis()+".txt";
        //2.设置下载的响应头消息  固定
        response.setHeader("content-disposition","attachment;filename="+s1);
        response.setCharacterEncoding("UTF-8");
        //3.查询下载的数据
        List<Pet> list = dao.selectAll();
        //4.IO流写出
        PrintWriter writer = response.getWriter();
        for (Pet pet : list) {
            writer.print(pet.toString());
        }
        writer.flush();
    }
}
